﻿// ===============================================================================
// XCI.NET 西安交通信息WinForm开发框架 2018 版权所有
// ===============================================================================
using System;
using System.ComponentModel;
using System.Data;
using System.Windows.Forms;
using DevExpress.XtraEditors;
using DevExpress.XtraGrid.Views.Grid;
using XCI.Core;
using XCI.Extensions;
using XCI.Windows.Extensions;
using XCI.Windows.Forms;
using XCI.Windows.Helper;

namespace XCI.Windows.Plugin.GridSetting.UI
{
    [ToolboxItem(false)]
    public partial class BaseGridTemplate : XtraUserControl
    {
        public BaseGridTemplate()
        {
            InitializeComponent();
        }

        protected virtual string GetId()
        {
            return string.Empty;
        }

        protected virtual string GetSetting()
        {
            return string.Empty;
        }

        protected virtual BoolMessage ApplySetting(string data)
        {
            return BoolMessage.True;
        }

        protected void Initialize()
        {
            LoadData();
        }

        private void LoadData()
        {
            var templateList = GridSettingManager.Instance.GetTemplates(GetId());
            DataTable table = new DataTable();
            table.Columns.Add(new DataColumn("Name"));
            templateList.ForEach(p =>
            {
                DataRow row = table.NewRow();
                row[0] = p;
                table.Rows.Add(row);
            });
            gridControl.DataSource = table;
        }

        /// <summary>
        /// 验证
        /// </summary>
        protected bool Validation(string name)
        {
            if (string.IsNullOrEmpty(GetId()))
            {
                MessageBoxHelper.ShowWarn("请指定表格标识");
                return false;
            }
            if (string.IsNullOrEmpty(name))
            {
                MessageBoxHelper.ShowWarn("请输入模板名称");
                return false;
            }
            return true;
        }
         

        private void editSearchBox_EditValueChanged(object sender, EventArgs e)
        {
            gridView1.ApplyFindFilter(((ButtonEdit)sender).Text.Trim());
        }

        private void gridView1_FocusedRowChanged(object sender, DevExpress.XtraGrid.Views.Base.FocusedRowChangedEventArgs e)
        {
            btnApply.Enabled = btnCopy.Enabled =
                btnDelete.Enabled = btnReName.Enabled = gridView1.FocusedRowHandle > -1;
        }

        private void gridView1_CustomDrawRowIndicator(object sender, RowIndicatorCustomDrawEventArgs e)
        {
            if (gridView1.OptionsView.ShowIndicator && e.Info.IsRowIndicator && e.RowHandle >= 0)
            {
                e.Info.DisplayText = (e.RowHandle + 1).ToString();
                e.Info.ImageIndex = -1;
            }
        }

        private void btnSave_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
        {
            var popmp = new FrmPrompt();
            if (popmp.ShowPromptDialog("请输入模板名称", string.Empty) == DialogResult.OK)
            {
                string name = popmp.InputText;
                if (!Validation(name)) return;
                string data = GetSetting();
                GridSettingManager.Instance.SaveTemplateSetting(GetId(), name, data).EnsureSuccess();
                Reload();
            }
            popmp.Dispose();
        }

        //private void btnReName_ItemClick(object sender, ItemClickEventArgs e)
        //{
        //    string oldName = gridView1.FocusedValue.ToStringOrEmpty();
        //    if (oldName.IsEmpty()) return;
        //    var popmp = new FrmPrompt();
        //    if (popmp.ShowPromptDialog("请输入模板新名称", oldName) == DialogResult.OK)
        //    {
        //        string newName = popmp.InputText;
        //        if (newName.Equals(oldName)) return;
        //        if (!Validation(newName)) return;
        //        var result = GridSettingManager.RenameTemplate(GridId, oldName, newName);
        //        Reload(result);
        //    }
        //    popmp.Dispose();
        //}

        private void btnCopy_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
        {
            string oldName = gridView1.FocusedValue.ToStringOrEmpty();
            if (oldName.IsEmpty()) return;
            var popmp = new FrmPrompt();
            if (popmp.ShowPromptDialog("请输入模板新名称", oldName) == DialogResult.OK)
            {
                string newName = popmp.InputText;
                if (!Validation(newName)) return;
                if (newName.Equals(oldName, StringComparison.OrdinalIgnoreCase))
                {
                    MessageBoxHelper.ShowWarn("新名称和旧名称不能一样");
                    return;
                }
                GridSettingManager.Instance.CopyTemplate(GetId(), oldName, newName).EnsureSuccess();
                Reload();
            }
            popmp.Dispose();
        }

        private void btnDelete_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
        {
            string oldName = gridView1.FocusedValue.ToStringOrEmpty();
            if (oldName.IsEmpty()) return;
            if (MessageBoxHelper.ShowWarnYesNo("确定要删除模板吗？") == DialogResult.Yes)
            {
                GridSettingManager.Instance.DeleteTemplateSetting(GetId(), oldName).EnsureSuccess();
                Reload();
            }
        }

        private void btnApply_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
        {
            string name = gridView1.FocusedValue.ToStringOrEmpty();
            if (name.IsEmpty()) return;
            if (MessageBoxHelper.ShowWarnYesNo("确定要应用模板吗？") == DialogResult.Yes)
            {
                var data = GridSettingManager.Instance.LoadTemplateSetting(GetId(), name);
                var result = ApplySetting(data);
                if (result.Success)
                {
                    GridSettingManager.Instance.SaveSetting(GetId(), data).EnsureSuccess();
                    var form = this.FindForm();
                    form?.Close();
                }
                else if (result.Msg.IsNotEmpty())
                {
                    MessageBoxHelper.ShowError(result.Msg);
                }
            }
        }

        private void Reload()
        {
            LoadData();
        }
    }
}
